﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Ession.MouseKeyboardLibrary;

namespace LanUserSeeUsingPing
{
    public partial class frmMain : Form
    {
        private List<LanUser> _userOnline = new List<LanUser>();
        public List<LanUser> UserOnline
        {
            get
            {
                return _userOnline;
            }
            set
            {
                _userOnline = value;
            }
        }
        public frmMain()
        {
            InitializeComponent();
            t = new Task(
     () =>
     {
         this.Invoke((Action)(() =>
                                       {
                                           lbllabel3.Text = "搜索中..";
                                       }));
         int count = end - start + 1;
         Task[] subT = new Task[count];
         try
         {
             for (int i = 0; i < LanUsers.Count; i++)
             {
                 subT[i] = new Task(
                     (l) =>
                     {
                         var u = (LanUser)l;
                         Ping myPing;
                         myPing = new Ping();

                         var reply = myPing.Send(u.IP, LanUser.TimeSpan);
                         if (reply.Status == IPStatus.Success)
                         {
                             u.State = "在线";
                             u.Mac = Dns.GetHostEntry(reply.Address).HostName;
                             UserOnline.Add(u);
                             this.Invoke((Action)(() =>
                              {

                                  //dgUsers.DataSource = null;
                                  //dgUsers.DataSource = LanUsers;
                                  dgUsers.Refresh();
                              }

      ));
                         }
                         else
                         {
                             u.State = "离线";
                             this.Invoke((Action)(() =>
                            {
                                //dgUsers.DataSource = null;
                                //dgUsers.DataSource = LanUsers;
                                dgUsers.Refresh();
                            }

    ));

                         }
                     }, LanUsers[i]);
             }
             for (int i = 0; i < count; i++)
             {
                 subT[i].Start();
             }
             Task.WaitAll(subT);

             LastUserCount = UserOnline.Count;// LanUsers.Count(u => u.State == "在线");

             this.Invoke((Action)(() =>
                                 {
                                     lbllabel3.Text = "搜索完成";
                                     //dgUsers.DataSource = null;
                                     dgUsers.DataSource = UserOnline;
                                     //dgUsers.Refresh();
                                     lbUserCount.Text = string.Format("在线用户数:{0}", UserOnline.Count);
                                 }

         ));


         }
         catch
         {
         }
     }
         );
        }

        private int userLimit = 2;
        private int TimeOut;
        private Task t;
        List<LanUser> LanUsers = new List<LanUser>();
        List<string> ScanRange = new List<string>();
        private void btnbutton1_Click(object sender, EventArgs e)
        {
            userLimit = int.Parse(txtUserCountLimit.Text);
            tmNotify.Interval = int.Parse(txtTm.Text);
            start = int.Parse(txtStart.Text);
            end = int.Parse(txtEnd.Text);
            LanUsers.Clear();
            UserOnline.Clear();
            ScanRange.Clear();
            TimeOut = int.Parse(txtTimeout.Text);
            LanUser.TimeSpan = TimeOut;
            ScanRange.Add(txtRange.Text);

            foreach (var range in ScanRange)
            {
                for (int i = start; i <= end; i++)
                {
                    LanUsers.Add(new LanUser() { IP = range + "." + i, State = "unKnown" });
                }
            }

            if (chkAuto.Checked)
            {
                tmNotify.Start();
            }
            dgUsers.DataSource = LanUsers;
            t.Start();
            btnbutton1.Enabled = false;
        }

        private int LastUserCount = 0;

        private void tmNotify_Tick(object sender, EventArgs e)
        {
            if (t.IsCompleted)
            {
                t = new Task(
      () =>
      {
          foreach (var lanUser in LanUsers)
          {
              lanUser.State = "unKnown";
          }
          UserOnline.Clear();
          int count = end - start + 1;
          Task[] subT = new Task[count];
          try
          {
              this.Invoke((Action)(() =>
                                        {
                                            lbllabel3.Text = "搜索中..";
                                            dgUsers.DataSource = LanUsers;
                                        }));
              for (int i = 0; i < LanUsers.Count; i++)
              {
                  subT[i] = new Task(
                      (l) =>
                      {
                          var u = (LanUser)l;
                          Ping myPing;
                          myPing = new Ping();

                          var reply = myPing.Send(u.IP, LanUser.TimeSpan);
                          if (reply.Status == IPStatus.Success)
                          {
                              u.State = "在线";
                              UserOnline.Add(u);
                              this.Invoke((Action)(() =>
                               {

                                   dgUsers.Refresh();
                               }

                          ));
                          }
                          else
                          {
                              u.State = "离线";
                              this.Invoke((Action)(() =>
                           {
                               //dgUsers.DataSource = null;
                               //dgUsers.DataSource = LanUsers;
                               dgUsers.Refresh();
                           }

                      ));

                          }
                      }, LanUsers[i]);
              }
              for (int i = 0; i < count; i++)
              {
                  subT[i].Start();
              }
              Task.WaitAll(subT);
              // (u => u.State == "在线");
              if (LastUserCount != UserOnline.Count)
              {
                  if (LastUserCount < UserOnline.Count)//增加了
                  {
                      notifyIcon1.ShowBalloonTip(5000);
                  }
                  LastUserCount = UserOnline.Count;

              }
              this.Invoke((Action)(() =>
                                  {
                                      lbllabel3.Text = "搜索完成";
                                      //dgUsers.DataSource = null;
                                      dgUsers.DataSource = UserOnline;
                                      //dgUsers.Refresh();

                                      lbUserCount.Text = string.Format("在线用户数:{0}    {1}", UserOnline.Count, DateTime.Now.ToShortTimeString());
                                      if (UserOnline.Count>=userLimit)
                                      {
                                         KeyboardSimulator.KeyPress(Keys.Enter);
                                      }
                                  }

          ));


          }
          catch
          {
          }

      }
          );
                t.Start();

            }
            else
            {
                lbllabel3.Text = "搜索中..";
            }

        }

        private void btnbutton2_Click(object sender, EventArgs e)
        {

        }

        private void btnbutton2_Click_1(object sender, EventArgs e)
        {

        }

        private int start;
        private int end;
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.Save();
        }


    }
}
